package com.zwy.ubts.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

/**
 * @Author zwy
 * @Description: 单例模式 Properties文件读取
 * @Date Created in 12:58 2022/12/23
 */
public class PropertiesFile {

    private  HashMap<String,String> hp = new HashMap<>();
    private static PropertiesFile propertiesFile = new PropertiesFile();

    private PropertiesFile(){
        this.Open("config.properties");
    }

    //用输入输出流作为参数进行加载
    private void Load(InputStream is) {
        Properties a =  new Properties();
        try {
            a.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //得到键集
        Set<Object> st = a.keySet();
        Iterator<Object> it =st.iterator();
        //遍历键集，将所得到的键值对存入容器中
        while(it.hasNext()) {
            String key = (String) it.next();
            String value = a.getProperty(key);
            hp.put(key, value);
        }
    }

    //也可以通过导入相对路径
    private void Open(String path) {
        System.out.println("open /"+path);
        //建立输入输出流
        InputStream is = null;

        is = Class.class.getResourceAsStream("/"+path);
        if (is == null){
            System.out.println("null - 1");
            String filePath = Thread.currentThread().getContextClassLoader().getResource(path).getFile();
            System.out.println("open "+filePath);
            try {
                is = new FileInputStream(filePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println(is);
        Load(is);
    }

    public PropertiesFile getInstance(){
        return propertiesFile;
    }

    //根据键取得对应的值
    public static String getKey(String key) {
        return propertiesFile.hp.get(key);
    }

}
